<?php
	/**
	 * AlreadySentCheck.php
	 * 
	 * Ensures that we don't re-upload already uploaded messages. We do this
	 * by keeping a log of all uploaded messages in uploaded.txt
	 * 
	 * TODO: Plenty of optimization possible
	 * 
	 * @author 		Martijn Dijksterhuis
	 * @license 	GPL v2.0
	 * @copyright 	2009
	 * @version		$id$
	 */

	class AlreadySentCheck 
	{
		
		/* Standard filename -------             */	
		const   SENTFILE = "./uploaded.txt";
		
		private $_filename;
		private $_sentlist;
		private $_logger;		
		
		public function __construct()
		{
			$this->_filename = AlreadySentCheck::SENTFILE; 
		}
		
		public function setLogger(Zend_Log $log)
		{
			$this->_logger = $log;
		}		
		
		/** 
		 * Initializes the class by attempting the load a previously saved list
		 * of uploaded messages. 
		 */
		
		public function init()
		{
				$this->_logger->log("Loading list ({$this->_filename}) of messages already sent",Zend_Log::INFO);
				$this->_sentlist = @file($this->_filename,FILE_IGNORE_NEW_LINES);
				if ($this->_sentlist===FALSE)
					$this->_logger->log("No previous list of duplicate entries found, starting from the beginning",Zend_Log::INFO);
		}
		
		/** 
		 * Not used. Sets the filename to use for loading / saving the check list
		 * 
		 * @param $filename file name to use for loading / saving the check list 
		 * @return 
		 */
		
		public function setFileName($filename)
		{
				$this->filename = $filename;		
		}
		
		/** 
		 * Check if the message passed has been sent already  
		 * 
		 * @param $mail Unique ID for the mailbox / mail message to flag as send
		 * @return bool true on finding a previous mail attempt
		 */

		public function check($mail)
		{
				if ($this->_sentlist!==FALSE)
				{
					// We need to check the complete list from the beginning 
					foreach($this->_sentlist as $row)
					 if ($row == $mail)
					 	return true;
				}
				return false;
		}
		
		/** 
		 * Adds an entry to the list of e-mails succesfully uploaded. 
		 * 
		 * @param $mail	Unique ID for the mailbox / mail message to flag as send
		 */
		
		public function addEntry($mail)
		{
				file_put_contents($this->_filename,$mail . PHP_EOL ,FILE_APPEND);		
		} 
		
	}